package com.wanmait.cookbook.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.sun.scenario.effect.impl.state.LinearConvolveRenderState.PassType;
import com.wanmait.cookbook.dao.AttentionDAO;
import com.wanmait.cookbook.dao.CityDAO;
import com.wanmait.cookbook.dao.ProvinceDAO;
import com.wanmait.cookbook.dao.UserinfoDAO;
import com.wanmait.cookbook.vo.City;
import com.wanmait.cookbook.vo.Pager;
import com.wanmait.cookbook.vo.Province;
import com.wanmait.cookbook.vo.Userinfo;



/**
 * Servlet implementation class UserInfoServlet
 */
@WebServlet("/UserInfoServlet")
@MultipartConfig()
public class UserInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserInfoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		String action=request.getParameter("action");
		if("savesession".equals(action)) {
			this.savesession(request, response);
		}else if("reviseUserinfo".equals(action)){
			this.reviseUserinfo(request, response);
		}else if("provinceId".equals(action)){
			this.provinceId(request, response);
		}else if("province".equals(action)) {
			this.province(request, response);
		}else if("userinfoCity".equals(action)) {			
			this.userinfoCtiy(request, response);
		}else if("updateUserinfo".equals(action)) {
			this.updateUserinfo(request, response);
		}else if("updatePassword".equals(action)) {
			this.updatePassword(request, response);
		}else if("login".equals(action)) {
			this.login(request, response);
		}else if("exit".equals(action)) {
			this.exit(request, response);
		}else if ("registe".equals(action)) {
			this.registe(request, response);
		}else if ("showAttentiuonUser".equals(action)) {
			this.showAttentiuonUser(request, response);
		}else if ("showPagerAttentiuonUser".equals(action)) {
			this.showPagerAttentiuonUser(request, response);
		}else if ("showFansUser".equals(action)) {
			this.showFansUser(request, response);
		}else if ("showPagerFansUser".equals(action)) {
			this.showPagerFansUser(request, response);
		}
	}
	private void exit(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("userinfo");
		response.sendRedirect(request.getContextPath());//重定向到登录界面
	}

	/**
	 *  展示粉丝
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void showFansUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Userinfo userinfo = (Userinfo)request.getSession().getAttribute("userinfo");
		int rows = AttentionDAO.getAttentionDAO().getFansUserByUserinfoIdRows(userinfo.getId());
		Pager pager = new Pager();
		pager.setPageSize(2);
		pager.setPageNo(1);
		pager.setPageCount(rows);
		request.setAttribute("pager", pager);
		List<Userinfo> userinfos = AttentionDAO.getAttentionDAO().getFansUserByUserinfoId(userinfo.getId(), pager);
		request.setAttribute("userinfos", userinfos);
		request.getRequestDispatcher("/usercenter/showFansUser.jsp").forward(request, response);
	}
	
	/**
	 *  展示粉丝分页用户
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void showPagerFansUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Userinfo userinfo = (Userinfo)request.getSession().getAttribute("userinfo");
		int rows = AttentionDAO.getAttentionDAO().getFansUserByUserinfoIdRows(userinfo.getId());
		Pager pager = new Pager();
		pager.setPageSize(2);
		pager.setPageCount(rows);
		
		String pageNo = request.getParameter("pageNo");
		if(Integer.parseInt(pageNo)<1) {
			pageNo="1";
		}
		if (Integer.parseInt(pageNo)>pager.getPageCount()) {
			pageNo=pager.getPageCount()+"";
		}
		pager.setPageNo(Integer.parseInt(pageNo));
		
		request.setAttribute("pager", pager);
		List<Userinfo> userinfos = AttentionDAO.getAttentionDAO().getFansUserByUserinfoId(userinfo.getId(), pager);
		request.setAttribute("userinfos", userinfos);
		request.getRequestDispatcher("/inc/ajaxInc/showFansUser.jsp").forward(request, response);
	}
	
	/**
	 *  展示关注用户
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void showAttentiuonUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Userinfo userinfo = (Userinfo)request.getSession().getAttribute("userinfo");
		int rows = AttentionDAO.getAttentionDAO().getAttentionUserByUserinfoIdRows(userinfo.getId());
		Pager pager = new Pager();
		pager.setPageSize(2);
		pager.setPageNo(1);
		pager.setPageCount(rows);
		request.setAttribute("pager", pager);
		List<Userinfo> userinfos = AttentionDAO.getAttentionDAO().getAttentionUserByUserinfoId(userinfo.getId(),pager);
		request.setAttribute("userinfos", userinfos);
		request.getRequestDispatcher("/usercenter/showAttentionUser.jsp").forward(request, response);
	}
	
	/**
	 *  展示分页用户
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void showPagerAttentiuonUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Userinfo userinfo = (Userinfo)request.getSession().getAttribute("userinfo");
		int rows = AttentionDAO.getAttentionDAO().getAttentionUserByUserinfoIdRows(userinfo.getId());
		Pager pager = new Pager();
		pager.setPageSize(2);
		pager.setPageCount(rows);
		
		String pageNo = request.getParameter("pageNo");
		if(Integer.parseInt(pageNo)<1) {
			pageNo="1";
		}
		if (Integer.parseInt(pageNo)>pager.getPageCount()) {
			pageNo=pager.getPageCount()+"";
		}
		pager.setPageNo(Integer.parseInt(pageNo));
		
		request.setAttribute("pager", pager);
		List<Userinfo> userinfos = AttentionDAO.getAttentionDAO().getAttentionUserByUserinfoId(userinfo.getId(),pager);
		request.setAttribute("userinfos", userinfos);
		request.getRequestDispatcher("/inc/ajaxInc/showAttentionUser.jsp").forward(request, response);
	}
	
	//修改密码
	protected void updatePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String password = request.getParameter("password");
		String id = request.getParameter("id");
		
		Userinfo userinfo = new Userinfo();
		
		userinfo.setPassword(password);
		userinfo.setId(Integer.parseInt(id));
		UserinfoDAO.getUserinfoDAO().updatePassword(userinfo);
		response.sendRedirect(request.getContextPath()+"/login.jsp");//重定向到登录界面
	}
	
	//锟结交锟斤拷
	protected void updateUserinfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    
	    HttpSession session = request.getSession();
	    
	    String id = request.getParameter("id");
	    String name = request.getParameter("nickname");
	    String telePhone = request.getParameter("telephone");
	    String userinfoBrithday = request.getParameter("birthday");
	    String selectSex = request.getParameter("selectSex");

	    String cityId = request.getParameter("cityId");
	    String kouwei = request.getParameter("kouwei");
	    String jieshao = request.getParameter("jieshao");
	    Part part = request.getPart("pic");
	    Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
	  
	    String head = part.getHeader("content-disposition");
	    int i = head.lastIndexOf(".");
	      String fileext = null;
	      String filepath = null;
	      String filename = null;    
	    if(i!=-1) {
	      fileext = head.substring(i,head.length()-1);
	      
	      filepath = request.getServletContext().getRealPath("/static/image");
	      
	      filename = UUID.randomUUID().toString();
	      
	      part.write(filepath+"/"+filename+fileext);
	      userinfo.setAvatar(filename+fileext);
	    
	    }
	    
	    part.delete();  
	    
	    City city = new City();
	    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	    format.setLenient(false);
	    Timestamp brithday=null;
	    try {
	      brithday = new Timestamp(format.parse(userinfoBrithday).getTime());
	    } catch (ParseException e) {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	    }
	    if(selectSex.equals("男")) {

	      userinfo.setSex(true);
	    }else {
	      userinfo.setSex(false);    
	    }
	    city.setId(Integer.parseInt(cityId));
	    
	    userinfo.setName(name);
	    userinfo.setTelephone(telePhone);
	    userinfo.setBirthday(brithday);
	    userinfo.setCity(city);
	    userinfo.setTaste(kouwei);
	    userinfo.setInfo(jieshao);    
	        
	    userinfo.setId(Integer.parseInt(id)); 
	    
	    session.setAttribute("userinfo", userinfo);
	    UserinfoDAO.getUserinfoDAO().updateUserinfo(userinfo,i);
	    
	    response.sendRedirect(request.getContextPath()+"/");
	  }
	protected void provinceId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String provinceId = request.getParameter("provinceId");
		List<City> provinceIds = (List<City>)CityDAO.getCityDAO().provinceAllCity(Integer.parseInt(provinceId));
		request.setAttribute("provinceIds", provinceIds);

		request.getRequestDispatcher("/usercenter/provinceHelper.jsp").forward(request, response);
	}
	//锟斤拷锟斤拷锟矫伙拷锟斤拷锟斤拷
	protected void userinfoCtiy(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		Integer userinfoCity = Integer.parseInt(request.getParameter("userinfoCity"));

		Integer userinfoCitys = CityDAO.getCityDAO().userinfoCity(userinfoCity);

		response.getWriter().print(userinfoCitys);
		
	}
	//锟斤拷锟斤拷锟斤拷锟叫筹拷锟斤拷
	protected void province(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String provinceId = request.getParameter("province");
		List<City> allCity = (List<City>)CityDAO.getCityDAO().allCity(Integer.parseInt(provinceId));
		request.setAttribute("allCity", allCity);
		request.getRequestDispatcher("/usercenter/CityHelper.jsp").forward(request, response);
	}
	//锟睫改革拷锟斤拷锟斤拷息
	protected void reviseUserinfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
				
		List<Province> allProvinces = (List<Province>) ProvinceDAO.getProvinceDAO().allProvince();
		request.setAttribute("allProvinces", allProvinces);
		request.getRequestDispatcher("/usercenter/personalInformation.jsp").forward(request, response);
		

	}
	protected void savesession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession();
		Userinfo userinfo=UserinfoDAO.getUserinfoDAO().login("锟斤拷锟斤拷", "222");
		int count=UserinfoDAO.getUserinfoDAO().getrows("锟斤拷锟斤拷", "222");
		int attention=UserinfoDAO.getUserinfoDAO().getattention("锟斤拷锟斤拷", "222");
		int cookbookCollect=UserinfoDAO.getUserinfoDAO().cookbookCollect("锟斤拷锟斤拷", "222");
		int worksCollect=UserinfoDAO.getUserinfoDAO().workCollect("锟斤拷锟斤拷", "222");
		//转锟斤拷
		session.setAttribute("cookbookCollect", cookbookCollect);
		session.setAttribute("worksCollect",worksCollect);
		session.setAttribute("count", count);
		session.setAttribute("userinfo", userinfo);
		session.setAttribute("attention", attention);
		request.getRequestDispatcher("/usercenter/myCollect.jsp").forward(request, response);
		
	}
	protected void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String code = request.getParameter("code");
		HttpSession session = request.getSession();
		String rightCode = (String) session.getAttribute("code");
		if (code == null || !code.equalsIgnoreCase(rightCode)) {
			response.sendRedirect(request.getContextPath() + "/login.jsp?msg=code");
			return;
		}
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String remenber = request.getParameter("remenber");
		Userinfo userinfo = UserinfoDAO.getUserinfoDAO().findByUsernameAndPassword(username, password);

		if (userinfo == null) {

			response.sendRedirect(request.getContextPath() + "/login.jsp?msg=error");

		} else {
			session.setAttribute("userinfo", userinfo);

			// 锟斤拷转锟斤拷锟斤拷录锟斤拷锟斤拷
			if ("1".equals(remenber))// 锟斤拷选锟斤拷选锟斤拷
			{
				Cookie cookieUsername = new Cookie("username", username);
				cookieUsername.setMaxAge(604800);// 锟斤拷锟斤拷cookie锟斤拷锟斤拷效时锟斤拷
				response.addCookie(cookieUsername);// 锟斤拷cookie锟斤拷锟捷凤拷锟酵革拷锟斤拷锟斤拷锟� 锟斤拷锟斤拷锟斤拷锟斤拷娴斤拷锟斤拷丶锟斤拷锟斤拷
			} else {
				Cookie cookieUsername = new Cookie("username", "");
				cookieUsername.setMaxAge(604800);// 锟斤拷锟斤拷cookie锟斤拷锟斤拷效时锟斤拷
				response.addCookie(cookieUsername);

				if (session.getAttribute("URL") == null) {
					response.sendRedirect(request.getContextPath());
				} else {
					response.sendRedirect((String) session.getAttribute("URL"));
				}

			}
		}
	}
	

/**
 *  娉ㄥ唽
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
protected void registe(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String username = request.getParameter("username");
  String password = request.getParameter("password");
  System.out.println("================");
  Boolean judgeUsername = UserinfoDAO.getUserinfoDAO().judgeUsername(username);
  if (judgeUsername) {
    request.setAttribute("username", username);
    request.setAttribute("error", "用户名已存在");
    request.getRequestDispatcher("/registe.jsp").forward(request, response);
  }else {
    Userinfo userinfo = new Userinfo();
    userinfo.setUsername(username);
    userinfo.setPassword(password);
    userinfo.setName("吃了吗");
    userinfo.setTaste("甜");
    userinfo.setAvatar("1.jpg");
    UserinfoDAO.getUserinfoDAO().registe(userinfo);
    request.getRequestDispatcher("/login.jsp").forward(request, response);
  }
}

	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
